package com.xy.config;

import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;

import java.util.Collections;
import java.util.HashMap;
import java.util.Map;

/**
 * Created by XiuYang on 2016/11/21.
 */
@Component
@ConfigurationProperties(prefix="imgUpload")
public class ImgUploadConfig {
    /**
     * 上传临时文件路径 windows
     */
    private String tmpFilePathWindows;
    /**
     * 上传临时文件路径 linux
     */
    private String tmpFilePathLinux;
    /**
     * 头像大小图配置
     */
    private Map<String,String> headPhotoSize;

    /**
     * 帖子图片大小图配置
     */
    private Map<String,String> articleImgSize;

    /**
     * 获取图片配置map
     * @param imgType 图片类型
     * @return
     */
    public Map<String,ImgSize> getImgConfig(int imgType){
        if(imgType == ImgConstant.ImgType.HEAD_PHOTO){
            return parseSize(headPhotoSize);
        }
        if(imgType == ImgConstant.ImgType.ARTICLE_IMG){
            return parseSize(articleImgSize);
        }
        return Collections.emptyMap();
    }

    /**
     * 临时文件路径
     */
    public String getTmpFilePath(){
        return "Windows_NT".equals(System.getenv("OS"))?tmpFilePathWindows:tmpFilePathLinux;
    }
    public Map<String, String> getHeadPhotoSize() {
        return headPhotoSize;
    }

    public void setHeadPhotoSize(Map<String, String> headPhotoSize) {
        this.headPhotoSize = headPhotoSize;
    }

    public Map<String, String> getArticleImgSize() {
        return articleImgSize;
    }

    public void setArticleImgSize(Map<String, String> articleImgSize) {
        this.articleImgSize = articleImgSize;
    }

    public String getTmpFilePathWindows() {
        return tmpFilePathWindows;
    }

    public void setTmpFilePathWindows(String tmpFilePathWindows) {
        this.tmpFilePathWindows = tmpFilePathWindows;
    }

    public String getTmpFilePathLinux() {
        return tmpFilePathLinux;
    }

    public void setTmpFilePathLinux(String tmpFilePathLinux) {
        this.tmpFilePathLinux = tmpFilePathLinux;
    }

    private Map<String,ImgSize> parseSize(Map<String,String> conf){

        Map<String,ImgSize> map = new HashMap<>();

        for(String key : conf.keySet()){
            String wh = conf.get(key);
            if(StringUtils.isEmpty(wh)){
                return null;
            }
            String[] config = wh.split("x");
            map.put(key,new ImgSize(Integer.parseInt(config[0]),Integer.parseInt(config[1])));
        }
        return map;
    }
}
